package cn.lyvust.shili02;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;

import java.sql.ResultSet;
import java.sql.Statement;

/**
 * Description:
 * date: 2021-5-25 20:13
 *
 * @author Guo_guo
 * @since JDK 1.8
 */
public class TestDB {
    public static void main(String[] args) {
        login("a' or 'a'='a", "a' or 'a'='a");
    }

    public static void login(String username, String password) {
        Connection conn = null;
        Statement stmt = null;
        ResultSet rs = null;
        try {
            String url = "jdbc:mysql://localhost:3306/student?user=root&password=123456";
            // 数据库执行的语句
            Class.forName("com.mysql.jdbc.Driver"); // 加载驱动
            conn = DriverManager.getConnection(url); // 获取数据库连接
            stmt = conn.createStatement();
            String sql = "SELECT * FROM stuinfo WHERE " + "username='" + username + "' and password='" + password + "'";
            rs = stmt.executeQuery(sql);
            if (rs.next()) {
                System.out.println("欢迎" + rs.getString("username"));
            } else {
                System.out.println("用户名或密码错误！");
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            try {
                if (rs != null)
                    rs.close(); // 关闭结果数据集
                if (stmt != null)
                    stmt.close(); // 关闭执行环境
                if (conn != null)
                    conn.close(); // 关闭数据库连接
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

}
